<template>
	<view class="to-record">
		<van-notice-bar left-icon="info-o" wrapable text="查看备案申请填报帮助" @click="toPreview" />

		<view class="body-contair">
			<view class="form-list">
				<view class="form-item form-align-top require-item">
					<span class="item-label">工程地点:</span>
					<!-- <p v-if="form.address" class="item-content item-input">
						{{ form.address ? form.address : "请选择工程地点" }}
					</p> -->
					<textarea class="item-content item-input" auto-height :value="form.address" :disabled="!addressInput && canEdit"
						placeholder="请输入工程地点" />
					<van-button v-if="canEdit" class="item-other divider" size="mini" @click="toSelectAddress">
						选择
					</van-button>
				</view>
				<view class="form-item require-item">
					<span class="item-label">工程名称:</span>
					<input class="item-content item-input" :value="form.proName" :disabled="!canEdit"
						placeholder="请输入工程名称" id="proName" @input="onInputChange" />
				</view>
				<view class="form-item require-item">
					<span class="item-label">设计单位:</span>
					<input class="item-content item-input" :value="form.designer" :disabled="!canEdit"
						placeholder="请输入设计单位" id="designer" @input="onInputChange" />
				</view>
				<view class="form-item require-item">
					<span class="item-label">建设方:</span>
					<input class="item-content item-input" :value="form.builder" :disabled="!canEdit"
						placeholder="请输入建设方" id="builder" @input="onInputChange" />
				</view>
				<view class="form-item require-item">
					<span class="item-label">现场负责人及联系方式:</span>
					<input class="item-content item-input" :value="form.builderContact" :disabled="!canEdit"
						placeholder="请输入建设方现场负责人及联系方式" id="builderContact" @input="onInputChange" />
				</view>
			</view>

			<view class="form-list">
				<view class="form-item require-item">
					<span class="item-label">结构形式:</span>
					<input class="item-content item-input" :value="form.struct" disabled placeholder="请选择结构形式"
						@click="onPopShow(true, 'struct')" />
				</view>
				<view class="form-item require-item">
					<span class="item-label">建筑面积:</span>
					<input class="item-content item-input" :value="form.area" :disabled="!canEdit" placeholder="请输入建筑面积"
						id="area" @input="onInputChange" />
				</view>
				<view class="form-item require-item">
					<span class="item-label">计划开工:</span>
					<input class="item-content item-input" :value="form.startDate" disabled placeholder="请选择计划开工时间"
						@click="onPopDateShow(true, 'startDate')" />
				</view>
				<view class="form-item require-item">
					<span class="item-label">计划完工:</span>
					<input class="item-content item-input" :value="form.endDate" disabled placeholder="请选择完工开工时间"
						@click="onPopDateShow(true, 'endDate')" />
				</view>
				<view class="form-item require-item">
					<span class="item-label">工程类型:</span>
					<p v-if="form.proType" class="item-content item-input" @click="onPopShow(true, 'proType')">
						{{ form.proType ? form.proType : "请选择工程类型" }}
					</p>
					<input v-if="!form.proType" class="item-content item-input" :value="form.proType" disabled
						placeholder="请选择工程类型" @click="onPopShow(true, 'proType')" />
				</view>
				<view class="form-item require-item">
					<span class="item-label">工程造价:</span>
					<input class="item-content item-input" :value="form.cost" :disabled="!canEdit" placeholder="请输入工程造价"
						id="cost" @input="onInputChange" />
				</view>
				<view class="form-item require-item">
					<span class="item-label">施工方:</span>
					<input class="item-content item-input" :value="form.worker" :disabled="!canEdit"
						placeholder="请输入施工方联系人" id="worker" @input="onInputChange" />
				</view>
				<view class="form-item require-item">
					<span class="item-label">现场负责人及联系方式:</span>
					<input class="item-content item-input" :value="form.workerContact" :disabled="!canEdit"
						placeholder="请输入施工方现场负责人及联系方式" id="workerContact" @input="onInputChange" />
				</view>
			</view>

			<view class="form-list upload-box" v-for="(imgItem, imgIndex) in imgList" :key="imgIndex">
				<view class="upload-title">
					<span class="require-icon" v-if="imgIndex != 0 && imgIndex != 6 && imgIndex != 8">*</span>
					{{ getUploadTitle(imgIndex) }}
				</view>
				<view class="upload-content">
					<van-uploader accept="image" :data-id="imgIndex" :file-list="imgItem" :disabled="!canEdit"
						@after-read="afterDocRead" @delete="onDeleteImage" />
				</view>
			</view>

			<view class="form-list">
				<view class="form-item require-item">
					<span class="item-label">联系手机:</span>
					<input class="item-content item-input" :disabled="verifyFlag || !canEdit" placeholder="请输入联系手机"
						type="number" :value="form.phone" id="phone" @input="onInputChange" />
				</view>

				<view class="form-item require-item" v-if="canEdit">
					<span class="item-label">验证码:</span>
					<input class="item-content item-input" :disabled="!verifyFlag" placeholder="请输入验证码"
						:value="verifyCode" @input="onInputVerifyCode" />
					<span class="item-other divider" @click="onSendValidCode">
						{{ verifyText }}
					</span>
				</view>
			</view>
		</view>

		<view class="footer-fixed" v-if="canEdit">
			<van-button class="footer-btn" type="info" round block color="#7C96F3" @click="submitForm('未提交')"
				:disabled="!verifyFlag">
				保存
			</van-button>
			<van-button class="footer-btn" type="info" round block color="#7C96F3" @click="submitForm('已提交，等待社区初审')"
				:disabled="!verifyFlag">
				保存并提交
			</van-button>
		</view>

		<van-popup :show="popShow" position="bottom" @close="onPopShow(false, null)">
			<van-picker show-toolbar :title="popTitle" :columns="popList" @cancel="onPopShow(false, null)"
				value-key="name" @confirm="onPopConfirm" />
		</van-popup>

		<van-popup :show="popDateShow" position="bottom" @close="onPopDateShow(false, null)">
			<van-datetime-picker type="date" :value="currentDate" :formatter="dateFormatter"
				@cancel="onPopDateShow(false, null)" @confirm="onSelectDate" />
		</van-popup>
	</view>
</template>

<script>
	import {
		getDataDic,
		sendValidCode,
		saveProjectApply,
		getProjectApplyById,
		getEditState
	} from "@/request/api.js";

	export default {
		data() {
			return {
				id: null,
				canEdit: true,
				addressInput: false,
				verifyFlag: false,
				form: {
					State: "",
					id: "",
					houseID: "",
					address: "",
					proName: "",
					designer: "",
					builder: "",
					builderContact: "",
					struct: "",
					area: "",
					startDate: "",
					endDate: "",
					proType: "",
					cost: "",
					worker: "",
					workerContact: "",
					phone: "",
					docsList: [],
				},
				imgList: [
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[]
				],
				popTitle: "",
				popType: null,
				popList: [],
				popShow: false,
				popDateShow: false,
				currentDate: null,
				dateFormatter(type, value) {
					if (type === "year") {
						return `${value}年`;
					}
					if (type === "month") {
						return `${value}月`;
					}
					return value;
				},

				verifyFlag: false,
				verifyText: "获取验证码",
				verifyOriCode: "",
				verifyCode: "",
				timeInt: null,
			};
		},
		async onLoad(e) {
			getEditState().then(res => {
				this.addressInput = res
			})

			if (e.edit == "true") {
				this.canEdit = true;
			}

			if (e.edit == "false") {
				this.canEdit = false;
			}

			if (e.id) {
				this.id = e.id;
				getProjectApplyById(e.id).then((res) => {
					let result = res.data[0];
					result.docsList.forEach((item) => {
						this.imgList[+item.name - 1].push({
							url: item.path,
						});
					});
					this.form = result;

					var aData = new Date(this.form.startDate.replaceAll('-','/'))
					var month = aData.getMonth() < 9 ? "0" + (aData.getMonth() + 1) : aData.getMonth() + 1;
					var date = aData.getDate() <= 9 ? "0" + aData.getDate() : aData.getDate();
					this.form.startDate = aData.getFullYear() + "/" + month + "/" + date;

					var bData = new Date(this.form.endDate.replaceAll('-','/'))
					var month = bData.getMonth() < 9 ? "0" + (bData.getMonth() + 1) : bData.getMonth() + 1;
					var date = bData.getDate() <= 9 ? "0" + bData.getDate() : bData.getDate();
					this.form.endDate = bData.getFullYear() + "/" + month + "/" + date;
				});
			}
		},
		onUnload(e) {
			if (this.timeInt) {
				clearInterval(this.timeInt);
				this.verifyText = "获取验证码"
			}
		},
		methods: {
			toPreview() {
				uni.showLoading({
					title: "正在下载...",
				});
				uni.downloadFile({
					url: this.$config.baseUrl + "/help/gcba.doc",
					success: (res) => {
						uni.showToast({
							title: "文件下载成功",
						});
						var filePath = res.tempFilePath;
						uni.openDocument({
							filePath: filePath,
							showMenu: true,
							success: (res) => {
								console.log("打开文档成功");
							},
						});
					},
					fail: () => {
						uni.showToast({
							icon: "none",
							title: "文件下载失败",
						});
					},
				});
			},

			submitForm(state) {
				let valid = this.validForm();
				if (valid) {
					let form = JSON.parse(JSON.stringify(this.form));

					let docsListTemp = [];
					let docsListIndex = 0;
					for (let i = 0; i < this.imgList.length; i++) {
						this.imgList[i].forEach((item) => {
							docsListTemp.push({
								name: i + 1,
								path: item.url,
								sortNO: docsListIndex++,
							});
						});
					}
					form.docsList = docsListTemp;
					form.State = state

					saveProjectApply(form).then((res) => {
						uni.navigateBack();
					});
				}
			},

			validForm() {
				for (let key in this.form) {
					if (key != "id" && !this.form[key]) {
						switch (key) {
							case "houseID":
							case "address":
								uni.showToast({
									icon: "none",
									title: "请选择工程地点",
								});
								return false;
							case "proName":
								uni.showToast({
									icon: "none",
									title: "请输入工程名称",
								});
								return false;
							case "designer":
								uni.showToast({
									icon: "none",
									title: "请输入设计单位",
								});
								return false;
							case "builder":
								uni.showToast({
									icon: "none",
									title: "请输入建设方",
								});
								return false;
							case "builderContact":
								uni.showToast({
									icon: "none",
									title: "请输入建设方现场联系人及电话",
								});
								return false;
							case "struct":
								uni.showToast({
									icon: "none",
									title: "请选择建筑结构",
								});
								return false;
							case "area":
								uni.showToast({
									icon: "none",
									title: "请输入建筑面积",
								});
								return false;
							case "startDate":
								uni.showToast({
									icon: "none",
									title: "请选择开始时间",
								});
								return false;
							case "startDate":
								uni.showToast({
									icon: "none",
									title: "请选择计划开工时间",
								});
								return false;
							case "endDate":
								uni.showToast({
									icon: "none",
									title: "请选择计划完工时间",
								});
								return false;
							case "proType":
								uni.showToast({
									icon: "none",
									title: "请选择工程类型",
								});
								return false;
							case "cost":
								uni.showToast({
									icon: "none",
									title: "请输入工程造价",
								});
								return false;
							case "worker":
								uni.showToast({
									icon: "none",
									title: "请输入施工方",
								});
								return false;
							case "workerContact":
								uni.showToast({
									icon: "none",
									title: "请输入施工方现场联系人及电话",
								});
								return false;
							default:
								break;
						}
					}
				}

				for (let i = 0; i < this.imgList.length; i++) {
					if ((i != 0 && i != 6 && i != 8) && this.imgList[i].length == 0) {
						uni.showToast({
							icon: "none",
							title: "请上传相关资料",
						});
						return false;
					}
				}

				if (!this.verifyCode || this.verifyCode != this.verifyOriCode) {
					uni.showToast({
						icon: "none",
						title: "短信验证码错误",
					});
					return false;
				}

				return true;
			},

			onInputChange(e) {
				this.form[e.target.id] = e.detail.value;
			},

			toSelectAddress() {
				if (this.canEdit) {
					uni.$on("handleSelectAddress", (item) => {
						this.form.houseID = item.houseID;
						this.form.address = item.address;
						this.form.area = item.area
						this.form.struct = item.struct
						this.form.designer = item.designer
					});
					uni.navigateTo({
						url: "../select_project_address/select_project_address?pageType=0&pageAll=true",
					});
				}
			},

			onPopShow(flag, type) {
				if (this.canEdit) {
					if (flag) {
						let _type = "";
						switch (type) {
							case "struct":
								_type = "Struct";
								this.popType = type;
								this.popTitle = "结构形式";
								break;
							case "proType":
								_type = "Project";
								this.popType = type;
								this.popTitle = "工程类型";
								break;
							default:
								break;
						}
						getDataDic(_type).then((res) => {
							this.popList = res.result;
							this.popShow = flag;
						});
					} else {
						this.popTitle = "";
						this.popList = [];
						this.popShow = flag;
					}
				}
			},

			onPopConfirm(e) {
				this.form[this.popType] = e.detail.value.name;
				this.onPopShow(false, null);
			},

			onPopDateShow(flag, type) {
				if (this.canEdit) {
					this.currentDate = flag ?
						this.form[type] ?
						new Date(this.form[type]).getTime() :
						new Date().getTime() :
						null;
					this.dateType = type;
					this.popDateShow = flag;
				}
			},

			onSelectDate(e) {
				let _date = new Date(parseInt(e.detail));
				this.form[this.dateType] = `${_date.getFullYear()}/${
        _date.getMonth() + 1 >= 10
          ? _date.getMonth() + 1
          : "0" + (_date.getMonth() + 1)
      }/${_date.getDate() >= 10 ? _date.getDate() : "0" + _date.getDate()}`;
				this.onPopDateShow(false, null);
			},

			getUploadTitle(index) {
				switch (index + 1) {
					case 1:
						return "1.规划批准文件或会商会办同意意见（扫描件或复印件）";
					case 2:
						return "2.建设方身份证明（扫描件或复印件）";
					case 3:
						return "3.建设方与施工方签订的合同及安全协议书（扫描件或复印件）";
					case 4:
						return "4.施工方的资质证书（扫描件或复印件，施工单位的还要提供安全生产许可证，建造师、监理工程师提供执业资格证，建筑工匠提供培训合格证）";
					case 5:
						return "5.施工方案和安全技术方案（扫描件或复印件，方案须经施工方的编制、审核审批以及建设方的批准，要有人员签字及单位盖章）";
					case 6:
						return "6.工伤保险或人身意外伤害保险（扫描件或复印件）";
					case 7:
						return "7.设计文件（按工程实际情况要求提供）";
					case 8:
						return "8.现场特种作业人员名单（扫描件或复印件）";
					case 9:
						return "9.其他资料";
					default:
						return "";
				}
			},

			afterDocRead(e) {
				const {
					file
				} = e.detail;
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				uni.uploadFile({
					url: this.$config.uploadUrl,
					filePath: file.url,
					name: "file",
					formData: {
						filetype: "image",
					},
					success: (res) => {
						// 上传完成需要更新 fileList
						const {
							result
						} = JSON.parse(res.data);
						this.imgList[e.target.dataset.id].push({
							...file,
							url: result,
						});
					},
				});
			},

			onDeleteImage(e) {
				if (this.canEdit) {
					this.imgList[e.target.dataset.id].splice(e.detail.index, 1);
				}
			},

			onInputVerifyCode(e) {
				this.verifyCode = e.detail.value;
			},

			onSendValidCode() {
				if (!this.form.phone) {
					uni.showToast({
						icon: "none",
						title: "请输入联系手机",
					});
					return;
				}

				if (this.timeInt) {
					return;
				} else {
					sendValidCode(this.form.phone).then((res) => {
						if (res.code == 1) {
							this.verifyOriCode = res.result;
							this.verifyFlag = true;
							this.setTimeInterval();
						}
					});
				}
			},

			setTimeInterval() {
				if (this.timeInt) {
					return;
				} else {
					let time = 30;
					this.verifyText = `${time}S 后重新发送`;
					this.timeInt = setInterval(() => {
						if (time <= 0) {
							clearInterval(this.timeInt);
							this.timeInt = null;
							this.verifyText = `重新发送`;
						} else {
							time--;
							this.verifyText = `${time}S 后重新发送`;
						}
					}, 1000);
				}
			},
		},
	};
</script>

<style lang="scss">
	.to-record {
		display: flex;
		flex-direction: column;
		background-color: #f8f8f8;
		height: 100vh;

		.body-contair {
			flex: 1;
			padding: 0 26rpx;
			overflow: scroll;

			.form-list {
				background-color: #ffffff;
				border-radius: 24rpx;
				font-size: 28rpx;
				margin: 20rpx 0;

				.form-item {
					display: flex;
					align-items: center;
					padding: 30rpx 35rpx;
					border-bottom: 1px solid #ededed;

					&:last-child {
						border-bottom: none;
					}

					.item-label {
						display: inline-block;
						width: 170rpx;
						text-align: right;
						padding-right: 20rpx;
					}

					.item-content {
						flex: 1;
						padding-right: 35rpx;
					}

					.item-radio {
						.radio-custom {
							margin-bottom: 22rpx;
							align-items: flex-start;
						}
					}

					.item-other {
						padding-left: 35rpx;
					}

					.divider {
						position: relative;

						&::before {
							display: block;
							content: "";
							position: absolute;
							top: 0;
							left: 0;
							width: 1px;
							height: 100%;
							background-color: #707070;
						}
					}
				}

				.form-align-top {
					align-items: flex-start;
				}

				.require-item {
					.item-label {
						display: inline-flex !important;
						justify-content: flex-end;
						align-items: flex-start;

						&::before {
							content: "*";
							color: red;
							margin-right: 6rpx;
						}
					}
				}
			}

			.upload-box {
				padding: 30rpx 35rpx;

				.upload-title {
					display: flex;
					align-items: flex-start;
					margin-bottom: 20rpx;

					.require-icon {
						color: red;
						margin-right: 6rpx;
					}
				}
			}
		}

		.footer-fixed {
			width: 100%;
			box-sizing: border-box;
			padding: 26rpx 38rpx;
			background-color: white;
			display: flex;

			.footer-btn {
				flex: 1;
				margin: 0 20rpx;
			}
		}
	}
</style>
